<?php

class Pictures_Image_UploadAction extends BlogPicturesBaseAction
{
    /**
     * Process HTTP POST request: process uploaded image and create preview images.
     *
     * @param AgaviRequestDataHolder $rd
     */
    public function executeWrite(AgaviRequestDataHolder $rd)
    {
        /* @var $model Pictures_PicturesModel */
        $model = $this->getContext()->getModel('Pictures', 'Pictures');
        $vm = $this->getContainer()->getValidationManager();
		$params = $rd->getParameters();
		$file = $rd->getFile('image');
		
		try {
		    $picture = $model->newPicture($file, $params['image_name']);
		} catch (PictureNotSupportedFormatException $e) {
		    $vm->setError('general', 'This file type is not supported.');
		    return 'Error';
		} catch (PictureDuplicateException $e) {
		    // report error if such image already exists
		    if (!isset($params['force_overwrite'])) {
		        $vm->setError('general', 'Image with such name already exist!');
		        return 'Error';
		    }
		    // overwrite the image
		    $picture = $model->getPicture(null, $params['image_name']);
		    try {
		        $model->updatePicture($picture, $file->tmp_name);
		    } catch (WereWordFilesystemException $e) {
		        $vm->setError('general', sprintf('Filesystem error: %s.', $e->getMessage()));
		        return 'Error';
		    }
		} catch (WereWordFilesystemException $e) {
		    $vm->setError('general', sprintf('Unable to save image! Filesystem error: %s. Please make sure that storage directory does exist and have appropriate access rights.', $e->getMessage()));
		    return 'Error';
		}
        
		return 'Success';
    }
    
	/**
	 * Returns the default view if the action does not serve the request
	 * method used.
	 *
	 * @return     mixed <ul>
	 *                     <li>A string containing the view name associated
	 *                     with this action; or</li>
	 *                     <li>An array with two indices: the parent module
	 *                     of the view to be executed and the view to be
	 *                     executed.</li>
	 *                   </ul>
	 */
	public function getDefaultViewName()
	{
		return 'Input';
	}
}

?>